#include "RenderTarget.h"
#include "DXDevice.h"

RenderTarget::RenderTarget(const char* name, int width, int height, bool depthStencil, int aa)
{
	char* newName = new char[strlen(name) + 7];
	sprintf(newName, "%s_color", name);
	colorTexture = TextureManager::GetInstance()->CreateTexture(newName, width, height, DXGI_FORMAT_R8G8B8A8_UNORM, D3D11_BIND_RENDER_TARGET, aa);
	SafeDeleteArray(newName);
	D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
	ZeroMemory(&renderTargetViewDesc, sizeof(renderTargetViewDesc));
	renderTargetViewDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
	renderTargetViewDesc.Texture2D.MipSlice = 0;
	HRESULT result = DXDevice::GetInstance()->GetD3D11Device()->CreateRenderTargetView(colorTexture->resource, &renderTargetViewDesc, &renderTargetView);
	if(FAILED(result))
	{
		return;
	}
	if(depthStencil)
	{
		newName = new char[strlen(name) + 14];
		sprintf(newName, "%s_depthStencil", name);
		depthStencilTexture = TextureManager::GetInstance()->CreateTexture(newName, width, height, DXGI_FORMAT_R24G8_TYPELESS, D3D11_BIND_DEPTH_STENCIL, 0);
		SafeDeleteArray(newName);
		D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
		ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
		depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
		depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
		depthStencilViewDesc.Flags = 0;
		depthStencilViewDesc.Texture2D.MipSlice = 0;
		HRESULT result = DXDevice::GetInstance()->GetD3D11Device()->CreateDepthStencilView(depthStencilTexture->resource, &depthStencilViewDesc, &depthStencilView);
		if(FAILED(result))
		{
			return;
		}
	}
	this->name  = new char[strlen(name) + 1];
	strcpy(this->name, name);
}
RenderTarget::~RenderTarget()
{
	TextureManager::GetInstance()->ReleaseTexure(colorTexture);
	TextureManager::GetInstance()->ReleaseTexure(depthStencilTexture);
	SafeRelease(renderTargetView);
	SafeRelease(depthStencilView);
	SafeDeleteArray(name);
}